<template>
  <div class="water-source-container">
    <!-- 水源地保护区概况 -->
    <el-card class="statistic-card" shadow="hover">
      <div slot="header" class="card-header">
        <h3 class="card-title">水源地保护区概况</h3>
      </div>
      <div class="overview-content">
        <el-statistic class="overview-item" :value="intakenumber" title="取水口个数" suffix="个"></el-statistic>
        <el-statistic class="overview-item" :value="sfirstprotectarea" title="一级保护区" suffix="km²"></el-statistic>
        <el-statistic class="overview-item" :value="ssecondprotectarea" title="二级保护区" suffix="km²"></el-statistic>
        <el-statistic class="overview-item" :value="squasiproctectarea" title="准保护区" suffix="km²"></el-statistic>
      </div>
    </el-card>


    <el-card class="statistic-card" shadow="hover" style="margin-top: 20px;">
      <div slot="header" class="card-header">
        <h3 class="card-title">达标情况分析</h3>
      </div>
      <div class="compliance-rate-container">
        <el-statistic class="compliance-rate-item" :value="qualityrate" title="水源地达标率" suffix="%"></el-statistic>
        <el-statistic class="compliance-rate-item" :value="yearqualityrate" title="同比" suffix="%"></el-statistic>
        <el-statistic class="compliance-rate-item" :value="prevqualityrate" title="环比" suffix="%"></el-statistic>
      </div>
      <div class="chart-container">
        <div ref="waterQualityChart" class="chart"></div>
      </div>
    </el-card>
    <el-card class="statistic-card" shadow="hover" style="margin-top: 20px;">
      <div slot="header" class="card-header" style="margin-top: 20px;">
        <h3 class="card-title">水源地分布情况统计</h3>
      </div>
      <div class="chart-container">
        <div ref="distributionChart" class="chart"></div>
      </div>
    </el-card>

    <!-- 行政区划分布 -->
    <el-card class="statistic-card" shadow="hover" style="margin-top: 20px;">
      <div slot="header" class="card-header">
        <h3 class="card-title">行政区划分布</h3>
      </div>
      <div class="chart-container">
        <div ref="administrativeChart" class="chart"></div>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

import { getDrinkwaterprotectinfo, getDrinkwaterqualityinfo, getDrinkwatercountyinfo, getDrinkwaterregioninfo } from "../../api/shuiyuandi.js";

export default {
  name: 'WaterSourceStatistics',

  data() {
    return {
      sfirstprotectarea: 0,
      ssecondprotectarea: 0,
      squasiproctectarea: 0,
      intakenumber: 0,
      prevqualityrate: 0,//环比
      yearqualityrate: 0,//同比
      qualityrate: 0,//水源地达标率

      // 图表实例
      waterQualityChart: null,
      distributionChart: null,
      administrativeChart: null,

      // 水质类型数据
      waterQualityData: {
        labels: [],
        datasets: [{
          data: [],
          backgroundColor: []
        }]
      },

      // 水源地分布数据
      // 水源地分布数据
      distributionData: {
        labels: [],
        datasets: [{
          data: [],
          backgroundColor: ['#a6c7ff', '#d9b3ff', '#73d2de', '#73e6ac']
        }]
      },

      // 行政区划数据
      // 行政区划数据
      administrativeData: {
        labels: [],
        datasets: [
          { label: '保护区', data: [], backgroundColor: '#5499c7' },
          { label: '取水口', data: [], backgroundColor: '#82e0aa' },
          { label: '监测点', data: [], backgroundColor: '#f7dc6f' }
        ]
      },
    }
  },
  mounted() {
    this.getOverviewData()
    this.getComplianceRateData()
    this.getDistributionData()
    this.getadministrativeData()
    this.initResize()
  },
  methods: {
    // 水质类型环形图
    initWaterQualityChart() {
      this.waterQualityChart = echarts.init(this.$refs.waterQualityChart)
      const waterQualityOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}个 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          data: this.waterQualityData.labels
        },
                grid: {
          left: '40%',
   
          containLabel: true
        },
        series: [
          {
            name: '水质类型',
            type: 'pie',
            radius: ['70%', '100%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 0,
              borderColor: '#fff',
              borderWidth: 0
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: this.waterQualityData.labels.map((label, index) => ({
              name: label,
              value: this.waterQualityData.datasets[0].data[index],
              itemStyle: {
                color: this.waterQualityData.datasets[0].backgroundColor[index]
              }
            }))
          }
        ]
      };
      this.waterQualityChart.setOption(waterQualityOption);
    },
    initDistributionChart() {
      // 水源地分布饼状图
      this.distributionChart = echarts.init(this.$refs.distributionChart)
      const distributionOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}个 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          data: this.distributionData.labels
        },
        series: [
          {
            name: '水源地类型',
            type: 'pie',
            radius: '80%',
            data: this.distributionData.labels.map((label, index) => ({
              name: label,
              value: this.distributionData.datasets[0].data[index],
              itemStyle: {
                color: this.distributionData.datasets[0].backgroundColor[index]
              }
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.distributionChart.setOption(distributionOption);
    },
    initAdministrativeChart() {
      // 行政区划分布柱状图
      this.administrativeChart = echarts.init(this.$refs.administrativeChart)
      const administrativeOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: this.administrativeData.datasets.map(item => item.label),
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.administrativeData.labels
        },
        yAxis: {
          type: 'value',
          name: '个'
        },
        series: this.administrativeData.datasets.map((dataset, index) => ({
          name: dataset.label,
          type: 'bar',
          data: dataset.data,
          itemStyle: {
            color: dataset.backgroundColor
          }
        }))
      };
      this.administrativeChart.setOption(administrativeOption);
    },
    processWaterQualityData(data) {
      // 定义水质类别顺序
      const qualityTypes = ['Ⅰ类', 'Ⅱ类', 'Ⅲ类', 'Ⅳ类', 'Ⅴ类', '劣Ⅴ类', '无类别'];

      // 定义颜色映射
      const colorMap = {
        'Ⅰ类': '#00b388',
        'Ⅱ类': '#33cc33',
        'Ⅲ类': '#ffd700',
        'Ⅳ类': '#ffa500',
        'Ⅴ类': '#ff4500',
        '劣Ⅴ类': '#ff0000',
        '无类别': '#cccccc'
      };

      // 清空原有数据
      this.waterQualityData.labels = [];
      this.waterQualityData.datasets[0].data = [];
      this.waterQualityData.datasets[0].backgroundColor = [];

      // 根据预定义顺序处理数据
      qualityTypes.forEach(type => {
        const countKey = `${type}count`;
        const rateKey = `${type}rate`;
        //console.log(type, data[countKey], data[rateKey])

        if (data.hasOwnProperty(countKey) && data[countKey] > 0) {
          // 只添加有数据的项到图表中
          this.waterQualityData.labels.push(`${type} (${data[countKey]}个, ${data[rateKey]}%)`);
          this.waterQualityData.datasets[0].data.push(data[countKey]);
          this.waterQualityData.datasets[0].backgroundColor.push(colorMap[type] || '#888888');
        }
      });

      if (this.waterQualityData.labels.length === 0) {
        this.waterQualityData.labels = ['暂无数据'];
        this.waterQualityData.datasets[0].data = [1];
        this.waterQualityData.datasets[0].backgroundColor = ['#cccccc'];
      }
      this.initWaterQualityChart()
    },
    processDistributionData(data) {
      // 清空原有数据
      this.distributionData.labels = [];
      this.distributionData.datasets[0].data = [];

      // 处理新的数据格式
      if (Array.isArray(data) && data.length > 0) {
        data.forEach(item => {
          this.distributionData.labels.push(item.drinkSourceLevelName);
          this.distributionData.datasets[0].data.push(item.count);
        });
      } else {
        // 如果没有数据，添加默认项
        this.distributionData.labels = ['暂无数据'];
        this.distributionData.datasets[0].data = [1];
      }

      // 重新初始化图表
      this.initDistributionChart();
    },
    processAdministrativeData(data) {
      // 清空原有数据
      this.administrativeData.labels = [];
      this.administrativeData.datasets.forEach(dataset => {
        dataset.data = [];
      });

      // 处理新的数据格式
      if (Array.isArray(data) && data.length > 0) {
        // 按县区分组数据
        const countyMap = new Map();

        data.forEach(item => {
          // 跳过空 county 值
          if (!item.county) return;

          if (!countyMap.has(item.county)) {
            countyMap.set(item.county, {
              '保护区': 0,
              '取水口': 0,
              '监测点': 0
            });
          }

          const countyData = countyMap.get(item.county);
          countyData[item.type] = (countyData[item.type] || 0) + item.count;
        });

        // 填充数据到 administrativeData
        countyMap.forEach((types, county) => {
          this.administrativeData.labels.push(county);
          this.administrativeData.datasets[0].data.push(types['保护区']);
          this.administrativeData.datasets[1].data.push(types['取水口']);
          this.administrativeData.datasets[2].data.push(types['监测点']);
        });
      } else {
        // 如果没有数据，添加默认项
        this.administrativeData.labels = ['暂无数据'];
        this.administrativeData.datasets.forEach(dataset => {
          dataset.data = [0];
        });
      }

      // 重新初始化图表
      this.initAdministrativeChart();
    },
    getOverviewData() {
      getDrinkwaterprotectinfo().then(res => {
        if (res.code === 200) {

          this.sfirstprotectarea = res.data.SFIRSTPROTECTAREA
          this.ssecondprotectarea = res.data.SSECONDPROTECTAREA
          this.squasiproctectarea = res.data.SQUASIPROCTECTAREA
          this.intakenumber = res.data.INTAKENUMBER
        }
      })
    },
    getComplianceRateData() {
      getDrinkwaterqualityinfo().then(res => {
        if (res.code === 200 && Array.isArray(res.data) && res.data.length >= 4) {
          this.qualityrate = res.data[0].qualityrate
          this.yearqualityrate = res.data[3].yearqualityrate
          this.prevqualityrate = res.data[2].prevqualityrate

          // 处理水质类型数据（res.data[1]）
          const qualityData = res.data[1];
          this.processWaterQualityData(qualityData);
        }
      }).catch(error => {
        console.error('获取饮水水质信息失败:', error)
      })
    },


    getDistributionData() {
      getDrinkwatercountyinfo().then(res => {
        if (res.code === 200) {
          let data = res.data
          this.processDistributionData(data)
        }
      })
    },

    getadministrativeData() {
      getDrinkwaterregioninfo().then(res => {
        if (res.code === 200) {
          let data = res.data
          this.processAdministrativeData(data)
        }
      })
    },

    // 监听窗口大小变化，重绘图表
    handleResize() {
      if (this.waterQualityChart) {
        this.waterQualityChart.resize();
      }
      if (this.distributionChart) {
        this.distributionChart.resize();
      }
      if (this.administrativeChart) {
        this.administrativeChart.resize();
      }
    },
    initResize() {


      // 监听窗口大小变化，重绘图表
      window.addEventListener('resize', this.handleResize);
    }
  }
}

</script>


<style scoped>
.water-source-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.statistic-card {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.overview-content {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px;
  padding: 10px 0;
  overflow-x: auto;
}

.overview-item {
  flex: 1;
  min-width: 100px;
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 15px;
  text-align: center;
  white-space: nowrap;
}

.compliance-rate-container {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
  padding: 10px 0;
}

.compliance-rate-item {
  text-align: center;
  flex: 1;
}

.chart-container {
  height: 300px;
  margin-top: 15px;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>

